package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowData;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowProperties;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowResponse;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.ByDayDto;
import com.zzyl.nursing.dto.FamilyRequestDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 *
 * @author syl
 * @date 2025-05-30
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IWechatService wechatService;

    @Autowired
    private TokenService tokenService;  //这是zzyl-framework模块中的

    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        String code = dto.getCode();
        String phoneCode = dto.getPhoneCode();

        // 调用微信接口返回openid
        String openid = wechatService.getOpenid(code);

        // 根据openid查询客户信息
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(queryWrapper);

//        String phone = wechatService.getPhone(phoneCode); //这里要注意获取手机号用的是phoneCode
        String phone = "15131041591"; //这里要注意获取手机号用的是phoneCode
        if (familyMember == null) {
            familyMember = new FamilyMember();
            familyMember.setPhone(phone);
            //从DEFAULT_NICKNAME_PREFIX随机挑选一个 + 手机号的后四位 0-8
            familyMember.setName(DEFAULT_NICKNAME_PREFIX.get(new Random().nextInt(DEFAULT_NICKNAME_PREFIX.size())) + phone.substring(7));
            familyMember.setOpenId(openid);
            familyMemberMapper.insert(familyMember);
        } else {
            // 这个用户是否修改过手机号
            if (!StrUtil.equals(familyMember.getPhone(), phone)) {
                familyMember.setPhone(phone);
            }
            familyMemberMapper.updateById(familyMember);

        }
        // 根据用户ID和昵称生成Jwt的token
        Map<String, Object> map = new HashMap();
        map.put("id", familyMember.getId());
        map.put("nickName", familyMember.getName());
        String token = tokenService.createToken(map); //这里注意把tokenService.createToken改成public

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    @Autowired
    private IElderService elderService;

    @Autowired
    private IFamilyMemberElderService familyMemberElderService;

    @Autowired
    private IDeviceDataService deviceDataService;

    @Override
    public void add(FamilyRequestDto dto) {
        //根据家属提供的信息，查询是否有此老人
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getName, dto.getName());
        queryWrapper.eq(Elder::getIdCardNo, dto.getIdCard());
        Elder elder = elderService.getOne(queryWrapper);

        if (elder == null) {
            throw new BaseException("查不到对应老人的信息");
        }

        //向中间表绑定家人信息
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setMemberId(UserThreadLocal.getUserId());
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setRemark(dto.getRemark());

        familyMemberElderService.save(familyMemberElder);

    }

    @Override
    public List<FamilyVo> queryFamilyAll() {
        List<FamilyVo> familyVoList = new ArrayList<>();

        //查询家人列表
        List<FamilyMemberElder> list = familyMemberElderService.list();
        for (FamilyMemberElder familyMemberElder : list) {
            Long elderId = familyMemberElder.getElderId();
            Elder elder = elderService.getById(elderId);
            FamilyVo familyVo = new FamilyVo();
            familyVo.setId(familyMemberElder.getId());
            familyVo.setFamilyMemberId(familyMemberElder.getMemberId());
            familyVo.setElderId(familyMemberElder.getElderId());
            familyVo.setElderName(elder.getName());
            familyVoList.add(familyVo);
        }

        return familyVoList;

    }

    @Override
    public List<ElderVO> queryFamilyPage() {
        return familyMemberMapper.queryFamilyPage();
    }

    @Autowired
    private IoTDAClient ioTDAClient;

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        List<DeviceDataVo> list = new ArrayList<>();


        // IOT查询数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("IOT设备查询失败");
        }

        List<DeviceShadowData> shadowList = response.getShadow();
        if (CollUtil.isNotEmpty(shadowList)) {


            DeviceShadowData deviceShadowData = shadowList.get(0);
            DeviceShadowProperties reported = deviceShadowData.getReported();
            String eventTimeStr = reported.getEventTime();//20250601 T 08 24 34 Z
            LocalDateTime eventTimeUTC = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeUTC);

            Object properties = reported.getProperties();
            JSONObject jsonObject = JSONUtil.parseObj(properties);
            jsonObject.forEach((key, value) -> {
                DeviceDataVo deviceDataVo = new DeviceDataVo();
                deviceDataVo.setFunctionId(key);
                deviceDataVo.setEventTime(eventTime);
                deviceDataVo.setValue(value);
                list.add(deviceDataVo);
            });
        }
        return list;
    }

    @Override
    public List<DayVo> queryDeviceDataListByDay(ByDayDto dto) {
        System.out.println(DateUtil.date(dto.getStartTime()));
        System.out.println(DateUtil.date(dto.getEndTime()));
        List<DayVo> dayVoList = familyMemberMapper.queryDeviceDataListByDay(dto);
        return dayVoList;
    }

    @Override
    public List<DayVo> queryDeviceDataListByWeek(ByDayDto dto) {
        System.out.println(DateUtil.date(dto.getStartTime()));
        System.out.println(DateUtil.date(dto.getEndTime()));
        List<DayVo> dayVoList = familyMemberMapper.queryDeviceDataListByWeek(dto);
        return dayVoList;

    }

    @Override
    public void deleteById(Long id) {
        familyMemberMapper.deleteByMemberId(id);
    }

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

}
